`timescale 1ns/1ps
`default_nettype none
// TinyBus 1主2从 译码器（零等待设计友好）
// 命中条件： (addr & ~MASK) == BASE ; 其中 MASK=区域大小-1（要求2的幂）
// 例：64KB DMEM 区域 => BASE=32'h0000_0000, MASK=32'h0000_FFFF
module tinybus_1x2 #(
  parameter SLV0_BASE = 32'h0000_0000,
  parameter SLV0_MASK = 32'h0000_FFFF, // 64KB
  parameter SLV1_BASE = 32'h4000_0000,
  parameter SLV1_MASK = 32'h0000_0FFF  // 4KB
)(
  input  wire        clk,
  input  wire        rstn,
  // ---- Master ----
  input  wire        m_req_valid,
  input  wire [31:0] m_req_addr,
  input  wire [31:0] m_req_wdata,
  input  wire [3:0]  m_req_be,
  input  wire        m_req_we,
  output wire        m_req_ready,
  output wire        m_rsp_valid,
  output wire [31:0] m_rsp_rdata,
  output wire        m_rsp_err,

  // ---- Slave0 ----
  output wire        s0_req_valid,
  output wire [31:0] s0_req_addr,
  output wire [31:0] s0_req_wdata,
  output wire [3:0]  s0_req_be,
  output wire        s0_req_we,
  input  wire        s0_req_ready,
  input  wire        s0_rsp_valid,
  input  wire [31:0] s0_rsp_rdata,
  input  wire        s0_rsp_err,

  // ---- Slave1 ----
  output wire        s1_req_valid,
  output wire [31:0] s1_req_addr,
  output wire [31:0] s1_req_wdata,
  output wire [3:0]  s1_req_be,
  output wire        s1_req_we,
  input  wire        s1_req_ready,
  input  wire        s1_rsp_valid,
  input  wire [31:0] s1_rsp_rdata,
  input  wire        s1_rsp_err
);

  wire sel0 = ((m_req_addr & ~SLV0_MASK) == SLV0_BASE);
  wire sel1 = ((m_req_addr & ~SLV1_MASK) == SLV1_BASE) & ~sel0; // 冲突时优先0

  // 分发到从设备
  assign s0_req_valid = m_req_valid & sel0;
  assign s0_req_addr  = m_req_addr;
  assign s0_req_wdata = m_req_wdata;
  assign s0_req_be    = m_req_be;
  assign s0_req_we    = m_req_we;

  assign s1_req_valid = m_req_valid & sel1;
  assign s1_req_addr  = m_req_addr;
  assign s1_req_wdata = m_req_wdata;
  assign s1_req_be    = m_req_be;
  assign s1_req_we    = m_req_we;

  // 主侧 ready：被选中的从设备 ready（零等待从设备里恒为1）
  assign m_req_ready = (sel0 ? s0_req_ready :
                       (sel1 ? s1_req_ready : 1'b1));

  // 主侧响应：从被选中的从设备复用；未命中返回“空响应”
  assign m_rsp_valid = (sel0 ? s0_rsp_valid :
                       (sel1 ? s1_rsp_valid : m_req_valid));
  assign m_rsp_rdata = (sel0 ? s0_rsp_rdata :
                       (sel1 ? s1_rsp_rdata : 32'h0000_0000));
  assign m_rsp_err   = (sel0 ? s0_rsp_err   :
                       (sel1 ? s1_rsp_err   : 1'b0));

endmodule
`default_nettype wire
